import asyncio
import datetime
import time
from random import randint

import socks
import telethon.errors
from telethon import functions, types
from Account import create_clients
from Automatization import do_tasks_ad_click, do_tasks_bots, do_tasks_groups
from Balance import check_balance
from Console import console
from Settings import DELAY_BETWEEN_SESSIONS, LTC_BOT_CHAT_NAME, USE_PROXY, LTC_BOT_USERNAME


async def process_account(client):
    if USE_PROXY:
        client.set_proxy((socks.SOCKS5,"IP","PORT"))
    #  http_prx = Proxy.selenium_proxy() if Proxy else None
    # if http_prx:
    #     console.send_notification("Using http proxy: {}".format(http_prx))
    
    try:
        await client.start()
    except Exception as e:
        print(e)
    console.warning(f"Current account is @{(await client.get_me()).username}")
    ltc_bot_chat=await client.find_dialog(LTC_BOT_CHAT_NAME)
    if not ltc_bot_chat:
        console.error("Could not find LTC bot chat.")
        raise IndexError("Could not find LTC bot chat.")
    # if not ltc_bot_chat and False:
    #     console.error("Could not find LTC bot chat.    Trying join to chat...")
    #     try:
    #         await client(functions.messages.StartBotRequest(
    #         bot=LTC_BOT_USERNAME,
    #         peer=LTC_BOT_USERNAME,
    #         start_param='0lDna'
    #         ))
            
    #     except telethon.errors.BotInvalidError:
    #         console.error("Invalid Bot username: %s (CHECK Settings.py)" % LTC_BOT_USERNAME)
    #         raise IndexError()
    #     except StartParamInvalidError:
    #         console.error("Could not join LTC bot chat.")
    #         raise IndexError()
    #     messages = await client.get_messages(await client.find_dialog(LTC_BOT_CHAT_NAME), limit=1)
    #     for message in messages:
    #         pass
        
    #     await client.disconnect()
    #     await process_account(client)
    #     return
        #raise IndexError()
    console.info("Leaving old groups")
    await client.leave_all_old_groups()
    console.info("Working with ad tasks")
    await do_tasks_ad_click(client,ltc_bot_chat)
    console.info("Working with bot tasks")
    await do_tasks_bots(client,ltc_bot_chat)
    console.info("Working with group tasks")
    await do_tasks_groups(client,ltc_bot_chat)
    await client.disconnect()
    




async def main():
    accounts = create_clients()
    if len(accounts) == 0:
        console.error('Add acount first')
        raise IndexError
    start_time=time.time()
    for account in range(len(accounts)):

        
        await process_account(accounts[account])
        if account!=len(accounts)-1:
            console.info("Switching to next account")
    #check_balance here
    await check_balance(start_time)
    delay=randint(DELAY_BETWEEN_SESSIONS[0], DELAY_BETWEEN_SESSIONS[1])
    console.info("Sleeping for {} minutes".format(delay))
    time.sleep(delay*60)
    
    #client = TelegramClient('some_name', api_id, api_hash)



if __name__ == '__main__':
    while True:
        try:
            asyncio.run(main())
        except IndexError:
            console.error('Critial error')
            accounts = create_clients()
            accounts[0].connect()
    
            accounts[0].notify_admins("Critial ERROR")
            accounts[0].disconnect()
            break
        except Exception as e:
            console.error("Error occured in main process: {}".format(e))
